﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace Team4sCMDB
{
    public partial class Main : Form
    {
        public bool isAdmin;
        public Model model;
        private Panel dip;
        private Dictionary<string, TextBox> attributeTextBoxes;
       
        public Main(bool isAdmin)
        {
            this.isAdmin = isAdmin;
            attributeTextBoxes = new System.Collections.Generic.Dictionary<string, TextBox>();
            dip = new Panel();
            this.Controls.Add(dip);

            InitializeComponent();

            loadStyleSearchBox();
            Locations();
            this.Text = "Team4S CMDB - Speed, South, Student, Smart";
            //model = new Model("Team4sCmdb.mdb");
            model = new Model("Team4sCmdb.accdb");
            
            // Settings listboxes
            listBox1.IntegralHeight = false;
            listBox2.IntegralHeight = false;
            listBox2.SelectionMode = SelectionMode.MultiExtended;
            
        }

        // Static info
        private static string toolStripSearchBox_standardText = "Zoek op CI nummer";
        

        #region SearchBox Text and Font changes

        private void loadStyleSearchBox()
        {
            toolStripSearchBox.Text = toolStripSearchBox_standardText;
            toolStripSearchBox.ForeColor = SystemColors.ControlDark;
            toolStripSearchBox.Font = new Font(this.Font, FontStyle.Italic);
            
        }

        private void toolStripSearchBox_Enter(object sender, EventArgs e)
        {
            if ((toolStripSearchBox.Text != toolStripSearchBox_standardText) && (toolStripSearchBox.Text != ""))
            {
                toolStripSearchBox.Text = toolStripSearchBox.Text;
                toolStripSearchBox.ForeColor = SystemColors.ControlText;
                toolStripSearchBox.Font = new Font(this.Font, FontStyle.Regular);
            }
            else
            {
                toolStripSearchBox.Text = "";
                toolStripSearchBox.ForeColor = SystemColors.ControlText;
                toolStripSearchBox.Font = new Font(this.Font, FontStyle.Regular);
            }
        }

        private void toolStripSearchBox_Leave(object sender, EventArgs e)
        {
            if (toolStripSearchBox.Text != String.Empty)
            {
                if (toolStripSearchBox.Text != toolStripSearchBox_standardText)
                {
                }
            }
            else
            {
                toolStripSearchBox.Text = toolStripSearchBox_standardText;
                toolStripSearchBox.ForeColor = SystemColors.ControlDark;
                toolStripSearchBox.Font = new Font(this.Font, FontStyle.Italic);
            }
        }

        #endregion


        public Dictionary<string, TextBox> AttributeTextBoxes
        {
            get { return attributeTextBoxes; }
            set { attributeTextBoxes = value; }
        }

        // Runtime Layout
        private void Locations()
        {
            // tlp loacation update
            tlpListBoxesLocation();

            // Dynamic information panel Location
            Point dipLocation = new Point((tlpListBoxes.Location.X + tlpListBoxes.Width + 3), (tlpListBoxes.Location.Y));
            dip.Location = dipLocation;

        }

        // tlpListBoxes location
        private void tlpListBoxesLocation() 
        {
            tlpListBoxes.Location = new Point(0, 3 + toolStripMain.Height);
        }

        // Resize Event
        private void Main_SizeChanged_1(object sender, EventArgs e)
        {
            Locations();
        }

        // Log Out
        private void toolStripLogoutButton_Click(object sender, EventArgs e)
        {
            // Show new login form
            Login login = new Login();
            this.Hide();
            login.ShowDialog();
            this.Close();
        }

        // Show a new empty datatable of the currently selected category
        private void toolStripNewItemButton_Click(object sender, EventArgs e)
        {
            this.Controls.Remove(dip);
            switch ((CiCategory)listBox1.SelectedItem)
            {
                case CiCategory.Server:
                    dip = AttributePanelCreator.createPanel(model.getServer(0), true, this);
                    break;
                case CiCategory.VirtueleServer:
                    dip = AttributePanelCreator.createPanel(model.getVirtualServer(0), true, this);
                    break;
                case CiCategory.PC:
                    dip = AttributePanelCreator.createPanel(model.getPc(0), true, this);
                    break;
                case CiCategory.NetwerkApparatuur:
                    dip = AttributePanelCreator.createPanel(model.getNetwerkApparaat(0), true, this);
                    break;
                case CiCategory.RandApparatuur:
                    dip = AttributePanelCreator.createPanel(model.getRandApparaat(0), true, this);
                    break;
                case CiCategory.Software:
                    dip = AttributePanelCreator.createPanel(model.getSoftwareItem(0), true, this);
                    break;
                //case CiCategory.Personeel:
                    //dip = AttributePanelCreator.createPanel(model.getPersoon(0), true, this);
                    //break;
            }

            this.Controls.Add(dip);
            Locations();
        }

        // Show new incident rapport window for the currently selected item
        private void toolStripReportIncidentButton_Click(object sender, EventArgs e)
        {
            Incident inc = new Incident(this, (CI)listBox2.SelectedItem);
            inc.ShowDialog();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            foreach (CiCategory ci in Enum.GetValues(typeof(CiCategory)))
            {
                listBox1.Items.Add(ci);
            }
            listBox1.SelectedIndex = 0;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Controls.Remove(dip);         
            listBox2.Items.Clear();
            List<CI> l = null;

            switch ((CiCategory)listBox1.SelectedItem)
            {
                case CiCategory.Server:
                    l = model.getServers();
                    break;
                case CiCategory.VirtueleServer:
                    l = model.getVirtualServers();
                    break;
                case CiCategory.PC:
                    l = model.getPcs();
                    break;
                case CiCategory.NetwerkApparatuur:
                    l = model.getNetwerkApparatuur();
                    break;
                case CiCategory.RandApparatuur:
                    l = model.getRandApparatuur();
                    break;
                case CiCategory.Software:
                    l = model.getSoftware();
                    break;
                //case CiCategory.Personeel:
                    //l = model.getPersoneel();
                    //break;
            }
            foreach (CI ci in l)
            {
                listBox2.Items.Add(ci);
            }
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Controls.Remove(dip);
            if (listBox2.SelectedItems.Count == 1)
            {
                CI selectedCI = (CI)listBox2.SelectedItem;
                switch (selectedCI.category)
                {
                    case CiCategory.Server:
                        dip = AttributePanelCreator.createPanel(model.getServer(selectedCI.foreignId), false, this);
                        break;
                    case CiCategory.VirtueleServer:
                        dip = AttributePanelCreator.createPanel(model.getVirtualServer(selectedCI.foreignId), false, this);
                        break;
                    case CiCategory.PC:
                        dip = AttributePanelCreator.createPanel(model.getPc(selectedCI.foreignId), false, this);
                        break;
                    case CiCategory.NetwerkApparatuur:
                        dip = AttributePanelCreator.createPanel(model.getNetwerkApparaat(selectedCI.foreignId), false, this);
                        break;
                    case CiCategory.RandApparatuur:
                        dip = AttributePanelCreator.createPanel(model.getRandApparaat(selectedCI.foreignId), false, this);
                        break;
                    case CiCategory.Software:
                        dip = AttributePanelCreator.createPanel(model.getSoftwareItem(selectedCI.foreignId), false, this);
                        break;
                    //case CiCategory.Personeel:
                        //dip = AttributePanelCreator.createPanel(model.getPersoon(selectedCI.foreignId), false, this);
                        //break;
                }
                this.Controls.Add(dip);
            }
            else 
            { 
                // Do nothing
            }
            Locations();
        }

        public void saveNewCi_Click(object sender, System.EventArgs e)
        {
            if (isAdmin == true)
            {
                String sqla;
                String sqlb = String.Empty;

                // Select the correct SQL
                switch ((CiCategory)listBox1.SelectedItem)
                {
                    case CiCategory.Server:
                        //sql moet aangepast worden aan nieuwe database
                        sqla = string.Format("INSERT INTO ci (OudCI, SerieNr, StatusNr, ModelType, Aanschafprijs, Aanschafdatum, LocatieNr) VALUES (\'{0}\',\'{1}\',{2},\'{3}\',{4},{5},{6});", attributeTextBoxes["OudCI"].Text, attributeTextBoxes["SerieNr"].Text, statusNaamToStatusNr(attributeTextBoxes["statusNaam"].Text), attributeTextBoxes["ModelNr"].Text, attributeTextBoxes["Aanschafprijs"].Text, attributeTextBoxes["Aanschafdatum"].Text, locatieNaamToLocatieNr(attributeTextBoxes["locatieNaam"].Text));
                        int newCi = model.executeScalar(sqla);
                        sqlb = string.Format("INSERT INTO server (CInr, Functionaliteit, IpAdresServer) VALUES ({0},\'{1}\',\'{2}\');", newCi, attributeTextBoxes["Functionaliteit"].Text, attributeTextBoxes["IpAdresServer"].Text);

                        break;
                    case CiCategory.VirtueleServer:
                        sqla = "";
                        break;
                    case CiCategory.PC:
                        sqla = "";
                        break;
                    case CiCategory.NetwerkApparatuur:
                        sqla = "";
                        break;
                    case CiCategory.RandApparatuur:
                        sqla = "";
                        break;
                    case CiCategory.Software:
                        sqla = "";
                        break;
                    //case CiCategory.Personeel:
                        //sqla = "";
                        //break;
                }

                model.executeNonQuery(sqlb);
            }
            else 
            {
                MessageBox.Show("U kunt dit CI niet opslaan","U bent niet ingelogd als beheerder");
            }
        }

        private int statusNaamToStatusNr(string statusNaam)
        {
            if(statusNaam == "Beschikbaar")
            {
                return 1;
            }
            else
            {
                return 1;
            }

        }

        private int locatieNaamToLocatieNr(string locatieNaam)
        {
            if (locatieNaam == "Tilburg")
            {
                return 1;
            }
            else
            {
                return 1;
            }

        }

        public void editCi_Click(object sender, System.EventArgs e)
        {
            if (isAdmin == true)
            {
                // update ci
            }
            else
            {
                MessageBox.Show("U kunt dit CI niet wijzigen", "U bent niet ingelogd als beheerder");
            }
        }

        private void toolStripReportButton_Click(object sender, EventArgs e)
        {
            //if (listBox2.SelectedItem == null)
            //{
                //MessageBox.Show("Selecteer eerst één of meerdere configuratie items.");
            //}
            //else
            //{
                # region get info

                DataTable report = null;

                /* Gebruik dit blok code als je alleen rapport wilt hebben van CI item
                for (int i = 0; i < listBox2.SelectedItems.Count; i++ )
                {
                    DataTable tempDataTable = null;
                    CI selectedCI = (CI)listBox2.SelectedItems[i];
                    switch (selectedCI.category)
                    {
                        case CiCategory.Server:
                            tempDataTable = model.getServer(selectedCI.foreignId);
                            break;
                        case CiCategory.VirtueleServer:
                            tempDataTable = model.getVirtualServer(selectedCI.foreignId);
                            break;
                        case CiCategory.PC:
                            tempDataTable = model.getPc(selectedCI.foreignId);
                            break;
                        case CiCategory.NetwerkApparatuur:
                            tempDataTable = model.getNetwerkApparaat(selectedCI.foreignId);
                            break;
                        case CiCategory.RandApparatuur:
                            tempDataTable = model.getRandApparaat(selectedCI.foreignId);
                            break;
                        case CiCategory.Software:
                            tempDataTable = model.getSoftwareItem(selectedCI.foreignId);
                            break;
                        case CiCategory.Personeel:
                            tempDataTable = model.getPersoon(selectedCI.foreignId);
                            break;
                    }
                    if (i == 0)
                    {
                        report = tempDataTable.Clone();
                    }

                    DataRow newRow = report.NewRow();

                    for (int j = 0; j < report.Columns.Count; j++)
                    {
                        newRow[j] = tempDataTable.Rows[0][j];
                    }
                    report.Rows.Add(newRow);
                    
                }
                report.TableName = ((CI)listBox2.SelectedItem).category.ToString();
                 * */
                # endregion
                                
                

                DataSet ds = new DataSet();

                // Report info
                # region report info
                // Report date and time
                string date = DateTime.Now.ToShortDateString();
                DataTable reportinfo = new DataTable();
                reportinfo.TableName = "Rapportinfo";
                reportinfo.Columns.Add("Rapport gegenereerd op:", typeof(string));
                reportinfo.Rows.Add(date);
                # endregion

                ds.Tables.Add(reportinfo);
                //ds.Tables.Add(report);


                DataTable hardware = model.getAlleHardware();
                hardware.TableName = "Hardware";
                ds.Tables.Add(hardware);

                DataTable categorieen = model.getOverzichtCategorieen();
                categorieen.TableName = "Categorieen";
                ds.Tables.Add(categorieen);

                DataTable software = model.getOverzichtSoftware();
                software.TableName = "Software";
                ds.Tables.Add(software);

                SaveFileDialog dialog = new SaveFileDialog();
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    CreateExcelFile.CreateExcelDocument(ds, dialog.FileName + @".xlsx");
                }
            //}
        }

        private void toolStripSearchButton_Click(object sender, EventArgs e)
        {
            // Check for input
            if ((!string.IsNullOrWhiteSpace(toolStripSearchBox.Text)) && (toolStripSearchBox.Text != toolStripSearchBox_standardText))
            {
                // Act on input
                this.Controls.Remove(dip);
                string sql = "";

                // Select the correct SQL
                switch ((CiCategory)listBox1.SelectedItem)
                {
                    case CiCategory.Server:
                        sql = "SELECT * FROM server WHERE CInr LIKE " + toolStripSearchBox.Text + ";";
                        break;
                    case CiCategory.VirtueleServer:
                        sql = "SELECT * FROM virtual_server WHERE CInr LIKE " + toolStripSearchBox.Text + ";";
                        break;
                    case CiCategory.PC:
                        sql = "SELECT * FROM pc WHERE CInr LIKE " + toolStripSearchBox.Text + ";";
                        break;
                    case CiCategory.NetwerkApparatuur:
                        sql = "SELECT * FROM netwerkapparatuur WHERE CInr LIKE " + toolStripSearchBox.Text + ";";
                        break;
                    case CiCategory.RandApparatuur:
                        sql = "SELECT * FROM randapparatuur WHERE CInr LIKE " + toolStripSearchBox.Text + ";";
                        break;
                    case CiCategory.Software:
                        sql = "SELECT * FROM software WHERE CInr LIKE " + toolStripSearchBox.Text + ";";
                        break;
                    //case CiCategory.Personeel:
                        //sql = "SELECT * FROM personeel WHERE CInr LIKE " + toolStripSearchBox.Text + ";";
                        //break;
                }

                // Find CI and show result
                DataTable dt = model.executeSelectStatement(sql);
                dip = AttributePanelCreator.createPanel(dt, false, this);

                this.Controls.Add(dip);
                Locations();
            }
            // Do nothing
        }

        private void toolStripSearchBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripSearchButton_Click(null, null);
            }
        }

        private void toolStripAddUserButton_Click(object sender, EventArgs e)
        {
            User user = new User(this.isAdmin);
            user.Show();
        }
        
    }
}
